const puppeteer = require('puppeteer')

const base = `https://movie.douban.com/subject/`
// const doubanId = '26997532'
// const videoBase = `https://movie.douban.com/trailer/219491`

// promise 定时函数
const sleep = time => new Promise(resolve => {
    setTimeout(resolve, time)
})



// 监听这个事件
process.on('message', async movies => {
    console.log('movies')
    console.log(movies)

    console.log('start visit the target page')

    //创建一个浏览器对象
    const browser = await puppeteer.launch({
        args: ['--no-sandbox'],
        dumpio: false
    })

    const page = await browser.newPage()

    for (let i = 0; i < movies.length; i++) {
        let doubanId = movies[i].doubanId

        //浏览器打开这个地址,并设置加载完毕后
        await page.goto(base + doubanId, {
            waitUntil: 'networkidle2'
        })

        await sleep(1000)


        const result = await page.evaluate(() => {
            var $ = window.$
            var it = $('.related-pic-video')

            if (it && it.length > 0) {
                var link = it.attr('href')
                var cover = it.find('img').attr('src')

                return {
                    link,
                    cover
                }
            }

            return {}
        })
        console.log('----------------------------result------------------------')
        console.log(result)

        let video
        if (result.link) {
            await page.goto(result.link, {
                waitUntil: 'networkidle2'
            })
            await sleep(2000)

            video = await page.evaluate(() => {
                var $ = window.$
                var it = $('source')

                if (it && it.length > 0) {
                    return it.attr('src')

                }

                return ''
            })
        }


        const data = {
            video,
            doubanId,
            cover: result.cover
        }


        console.log('video')
        console.log(data)

        // console.log(result)

        process.send(data)
    }

    browser.close();
    process.exit(0)


})